﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MethodWorx.CMS.Content;
using MethodWorx.CMS.Plugins;
using MethodWorx.CMS.Services;

namespace MethodWorx.CMS.Workflow.PublishPage
{
    public class PublishPageWorkflowComponent : WorkflowComponent<PublishPageConfigurationController>
    {
        public PublishPageWorkflowComponent(Plugin plugin)
            : base(plugin)
        {
        }

        public static Guid ComponentId = Guid.Parse("{FF90AE19-ACAB-41D7-A682-781AB427F6D3}");

        public override Guid Id
        {
            get { return ComponentId;  }
        }

        public override string Category
        {
            get { return "Content";  }
        }

        public override string Name
        {
            get { return "Publish Page";  }
        }

        public override string Description
        {
            get { return "Published the chosen page";  }
        }

        public override string View
        {
            get { return "PublishPageConfigurationView.ascx"; }
        }

        public override StepExecutionResult Execute(IWorkflowExecutionContext context, IWorkflowConfiguration configuration)
        {
            //
            //  ok, here we go..
            var currentPage = context.GetWorkflowValue("currentPage") as Page;
            var config = configuration as PublishPageConfiguration;

            if (currentPage != null && config != null)
            {
                //  ok find the item in the context first
                var page = context.GetWorkflowValue(config.Page.TrimStart('{').TrimEnd('}')) as Page;
                //  then look in the current page
                if (page == null)
                    page = currentPage.ChildPages.FirstOrDefault(c => c.Name.ToLower() == this.ParseString(config.Page, context.GetAllWorkflowValues()).ToLower());

                if (page == null)
                    return StepExecutionResult.Error("Page Not Found");

                //
                //  else, lets publish
                ContentService service = new ContentService(context.CmsDataProvider);
                service.PublishPage(page.Id);

                return StepExecutionResult.Ok();
            }
            else
                return StepExecutionResult.Error("Unexpected error, invalid configuration");
        }
    }
}
